package com.rchat.pocmini.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.airtalkee.sdk.AirtalkeeAccount;
import com.aso.common.http.bean.BaseBean;
import com.aso.common.http.delegate.HttpCallbackImpl;
import com.aso.common.http.utils.HttpUtils;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.itsdf07.alog.ALog;
import com.rchat.pocmini.R;
import com.rchat.pocmini.activity.bean.GroupBean;
import com.rchat.pocmini.activity.view.location.MyOrientationListener;
import com.rchat.pocmini.bean2eventbus.LocationReportChannelBean;
import com.rchat.pocmini.bean2eventbus.LocationReportFreqBean;
import com.rchat.pocmini.global.HttpCodeGlobal;
import com.rchat.pocmini.global.HttpNodeGlobal;
import com.rchat.pocmini.global.RequestParam;
import com.rchat.pocmini.global.UrlsGlobal;
import com.rchat.pocmini.util.PhoneUtil;
import com.rchat.pocmini.util.SPUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by ljd on 2017/8/24.
 */

public class LocationReportService extends Service {


    private boolean isOpenLocationReport = false;

    /**
     * 频道监听上报
     */
    private static final int LISTEN_CHANNEL_REPORT = 0;

    /**
     * 最新一次的经纬度
     */
    private double mCurrentLan;//纬度
    private double mCurrentLon;//经度


    private int curReportFreq = LocationReportFreqBean.LOCATION_REPORT_3_M;

    /**
     * 方向定位监听器
     */
    private MyOrientationListener mOrientationListener;
    private int mXDirection;


    /**
     * 用户监听的频道
     */
    private List<GroupBean> curListenChannelList = new ArrayList<>();

    /**
     * 正在上报的用户监听的频道
     */
    private List<GroupBean> curReportListenChannelList = new ArrayList<>();


    private boolean isListenerChannelReport = false;


    /**
     * 是否有更新监听的频道
     */
    private boolean isUpdateListenChannel = false;


    private CoordinateConverter converter;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_REDELIVER_INTENT;
    }

    /**
     * gps
     */
    private LocationManager locationManager;
    private Location mLocation;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private Handler locationReportHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            List<String> groupIdList = new ArrayList<>();
            switch (msg.what) {
                case LISTEN_CHANNEL_REPORT:
                    if (curReportListenChannelList == null || curReportListenChannelList.size() == 0 || curReportListenChannelList.isEmpty()) {
                        curReportListenChannelList = curListenChannelList;
                    }
                    StringBuilder sb = new StringBuilder();

                    for (GroupBean bean : curReportListenChannelList) {
//                        if(bean.isLocked()){
//                            continue;
//                        }
                        groupIdList.add(bean.getGroupId());
                    }
//                    for (int i = 0;i<groupIdList.size();i++){
//                        if(i==groupIdList.size()-1){
//                            sb.append(groupIdList.get(i));
//                        }else {
//                            sb.append(groupIdList.get(i)).append(",");
//                        }
//                    }
                    if (!isOpenLocationReport) {
                        locationReportHandler.removeMessages(LISTEN_CHANNEL_REPORT);
                        return;
                    }
                    if (!groupIdList.isEmpty() && groupIdList.size() != 0) {
                        Log.e("aaa", "上报了");
                        reportLocation(groupIdList);
                        locationReportHandler.sendEmptyMessageDelayed(LISTEN_CHANNEL_REPORT, curReportFreq);
                    }
                    break;
//                case ENTER_CHANNEL_REPORT:
//                    initBDSdk();
//                    if(curReportEnterChannel.equals("")){
//                        curReportEnterChannel = curEnterChannel;
//                    }
//                    groupIdList.add(curReportEnterChannel);
//                    reportLocation(groupIdList);
//                    locationReportHandler.sendEmptyMessageDelayed(ENTER_CHANNEL_REPORT,REPORT_FREQ_30_S);
//                    break;
            }
        }
    };


    @Override
    public void onCreate() {
        super.onCreate();

        EventBus.getDefault().register(this);

        isOpenLocationReport = (boolean) SPUtil.get(getApplicationContext(), SPUtil.SPKeyGlobal.KEY_LOCATION_REPORT, false);

        if (isOpenLocationReport && PhoneUtil.isGpsEnable(this)) {
            initGps();
            curReportFreq = (int) SPUtil.get(getApplicationContext(), SPUtil.SPKeyGlobal.KEY_LOCATION_REPORT_FREQ, -1);
        }
    }

    private void initGps() {
        // 开启定位图层
        initOrientationListener();
        mOrientationListener.start();
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
            mLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (mLocation != null) {
                mCurrentLan = mLocation.getLatitude(); // 经度
                mCurrentLon = mLocation.getLongitude(); // 纬度
            }
        } else {
            Toast.makeText(this, R.string.open_gps, Toast.LENGTH_SHORT).show();

        }


    }

    private void uninitGps() {
        mOrientationListener = null;
        locationManager.removeUpdates(locationListener);
//        mOrientationListener.stop();
    }

    LocationListener locationListener = new LocationListener() {
        // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        // Provider被enable时触发此函数，比如GPS被打开
        @Override
        public void onProviderEnabled(String provider) {
        }

        // Provider被disable时触发此函数，比如GPS被关闭
        @Override
        public void onProviderDisabled(String provider) {
        }

        // 当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                mLocation = location;
                mCurrentLan = location.getLatitude(); // 经度
                mCurrentLon = location.getLongitude(); // 纬度
            }
        }
    };


    private void initOrientationListener() {
        mOrientationListener = new MyOrientationListener(this);
        mOrientationListener
                .setOnOrientationListener(new MyOrientationListener.OnOrientationListener() {
                    @Override
                    public void onOrientationChanged(float x) {
                        mXDirection = (int) x;
                    }
                });
    }


    private void reportLocation(List<String> groupIdList) {
        if (mLocation == null) {
            return;
        }

        JSONObject root = null;
        try {
            root = RequestParam.buildGeneralParam(HttpCodeGlobal.REQ_CODE_1224);
            JSONObject data = new JSONObject();
            data.put(HttpNodeGlobal.NodeReqPlatform, RequestParam.REQUEST_PLATFORM);
            data.put(HttpNodeGlobal.NodeReqVersion, HttpCodeGlobal.getUrlVersion(HttpCodeGlobal.REQ_CODE_1223));
            data.put(HttpNodeGlobal.NodeReqEnterprise, RequestParam.REQUEST_ENTERPRISE);
            data.put("userName", AirtalkeeAccount.getInstance().getUserId());
            data.put("displayName", AirtalkeeAccount.getInstance().getUserName());

            converter = new CoordinateConverter();
            // 将GPS设备采集的原始GPS坐标转换成百度坐标    
            converter.from(CoordinateConverter.CoordType.GPS);
            // sourceLatLng待转换坐标

            converter.coord(new LatLng(mCurrentLan, mCurrentLon));
            LatLng desLatLng = converter.convert();

            Log.e("longitude", desLatLng.longitude + "");
            Log.e("latitude", desLatLng.latitude + "");

            data.put("longitude", desLatLng.longitude);
            data.put("latitude", desLatLng.latitude);
            data.put("direction", mXDirection);
            JSONArray groups = new JSONArray();
            for (String group : groupIdList) {
                groups.put(group);
            }
            data.put("groupIds", groups);

            root.put("data", data);
        } catch (JSONException e) {
            e.printStackTrace();
            return;
        }

        //上报自己的定位信息
        HttpUtils.postAsyn(UrlsGlobal.getUrl(UrlsGlobal.LOCATION_REPORT), root.toString(), new HttpCallbackImpl<BaseBean>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(BaseBean bean) {
                ALog.d("desc = %s", bean.getDesc());
                if (isUpdateListenChannel) {
                    curReportListenChannelList = curListenChannelList;
                    isUpdateListenChannel = false;
                }
            }

            @Override
            public void onFailureResult(BaseBean bean) {
                ALog.d("code = %s,message = %s", bean.getCode(), bean.getDesc());
            }

            @Override
            public void onFinish() {

            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        locationReportHandler.removeMessages(LISTEN_CHANNEL_REPORT);
        uninitGps();
//        locationReportHandler.removeMessages(ENTER_CHANNEL_REPORT);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusAddLocationReportChannel(LocationReportChannelBean bean) {

        switch (bean.getCurChannelEvent()) {
            case LocationReportChannelBean.CHANNEL_EVENT_LISTEN:
                if (bean.getListenChannelList() == null || bean.getListenChannelList().size() == 0 || bean.getListenChannelList().isEmpty()) {
                    locationReportHandler.removeMessages(LISTEN_CHANNEL_REPORT);
                    isListenerChannelReport = false;
                    return;
                }
                curListenChannelList.clear();
                curListenChannelList.addAll(bean.getListenChannelList());
                if (!isOpenLocationReport) {
                    return;
                }
                isUpdateListenChannel = true;
                if (!isListenerChannelReport) {
                    isListenerChannelReport = true;
                    locationReportHandler.sendEmptyMessageDelayed(LISTEN_CHANNEL_REPORT, 0);
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusLocationReportFreqChange(LocationReportFreqBean bean) {
        locationReportHandler.removeMessages(LISTEN_CHANNEL_REPORT);
        switch (bean.getCurrentEvent()) {
            case LocationReportFreqBean.LOCATION_REPORT_CLOSE:
                if (isOpenLocationReport) {
                    uninitGps();
                }
                isOpenLocationReport = false;
                Log.e("aaa", "close:" + bean.getCurrentEvent());
                SPUtil.put(getApplicationContext(), SPUtil.SPKeyGlobal.KEY_LOCATION_REPORT_FREQ, -1);
                SPUtil.put(getApplicationContext(), SPUtil.SPKeyGlobal.KEY_LOCATION_REPORT, false);
                locationReportHandler.removeMessages(LISTEN_CHANNEL_REPORT);
                break;
            case LocationReportFreqBean.LOCATION_REPORT_5_S:
                if (!isOpenLocationReport) {
                    initGps();
                }
                isOpenLocationReport = true;
                curReportFreq = 5 * 1000;
                SPUtil.put(getApplicationContext(), SPUtil.SPKeyGlobal.KEY_LOCATION_REPORT_FREQ, curReportFreq);
                SPUtil.put(getApplicationContext(), SPUtil.SPKeyGlobal.KEY_LOCATION_REPORT, true);
                locationReportHandler.sendEmptyMessageDelayed(LISTEN_CHANNEL_REPORT, 0);
                break;
            case LocationReportFreqBean.LOCATION_REPORT_10_S:
                if (!isOpenLocationReport) {
                    initGps();
                }
                isOpenLocationReport = true;
                curReportFreq = 10 * 1000;
                SPUtil.put(getApplicationContext(), SPUtil.SPKeyGlobal.KEY_LOCATION_REPORT_FREQ, curReportFreq);
                SPUtil.put(getApplicationContext(), SPUtil.SPKeyGlobal.KEY_LOCATION_REPORT, true);
                locationReportHandler.sendEmptyMessageDelayed(LISTEN_CHANNEL_REPORT, 0);
                break;
            case LocationReportFreqBean.LOCATION_REPORT_30_S:
                if (!isOpenLocationReport) {
                    initGps();
                }
                isOpenLocationReport = true;
                curReportFreq = 30 * 1000;
                SPUtil.put(getApplicationContext(), SPUtil.SPKeyGlobal.KEY_LOCATION_REPORT_FREQ, curReportFreq);
                SPUtil.put(getApplicationContext(), SPUtil.SPKeyGlobal.KEY_LOCATION_REPORT, true);
                locationReportHandler.sendEmptyMessageDelayed(LISTEN_CHANNEL_REPORT, 0);
                break;
            case LocationReportFreqBean.LOCATION_REPORT_1_M:
                if (!isOpenLocationReport) {
                    initGps();
                }
                isOpenLocationReport = true;
                curReportFreq = 60 * 1000;
                SPUtil.put(getApplicationContext(), SPUtil.SPKeyGlobal.KEY_LOCATION_REPORT_FREQ, curReportFreq);
                SPUtil.put(getApplicationContext(), SPUtil.SPKeyGlobal.KEY_LOCATION_REPORT, true);
                locationReportHandler.sendEmptyMessageDelayed(LISTEN_CHANNEL_REPORT, 0);
                break;
            case LocationReportFreqBean.LOCATION_REPORT_3_M:
                if (!isOpenLocationReport) {
                    initGps();
                }
                isOpenLocationReport = true;
                curReportFreq = 3 * 60 * 1000;
                SPUtil.put(getApplicationContext(), SPUtil.SPKeyGlobal.KEY_LOCATION_REPORT_FREQ, curReportFreq);
                SPUtil.put(getApplicationContext(), SPUtil.SPKeyGlobal.KEY_LOCATION_REPORT, true);
                locationReportHandler.sendEmptyMessageDelayed(LISTEN_CHANNEL_REPORT, 0);
                break;
            case LocationReportFreqBean.LOCATION_REPORT_10_M:
                if (!isOpenLocationReport) {
                    initGps();
                }
                isOpenLocationReport = true;
                curReportFreq = 10 * 60 * 1000;
                SPUtil.put(getApplicationContext(), SPUtil.SPKeyGlobal.KEY_LOCATION_REPORT_FREQ, curReportFreq);
                SPUtil.put(getApplicationContext(), SPUtil.SPKeyGlobal.KEY_LOCATION_REPORT, true);
                locationReportHandler.sendEmptyMessageDelayed(LISTEN_CHANNEL_REPORT, 0);
                break;
            case LocationReportFreqBean.LOCATION_REPORT_10_S_FOR_ENTER_LOCATION_ACTIVITY:
                if (!isOpenLocationReport) {
                    initGps();
                }
                isOpenLocationReport = true;
                curReportFreq = 10 * 1000;
                locationReportHandler.sendEmptyMessageDelayed(LISTEN_CHANNEL_REPORT, 0);
                break;

        }
    }


}
